package com.maserb.monitor.remote;

import com.maserb.monitor.dataCenter.communication.MonitorMessageProtocol;
import com.maserb.monitor.dataCenter.communication.ReceiveConverter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class AFSTMessageDecoder extends ByteToMessageDecoder {
    final int HEAD_LENGTH = 10;


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buffer, List<Object> out) {
        if (buffer.readableBytes() < HEAD_LENGTH) {
            return;
        }

        int beginIndex = buffer.readerIndex();
        byte[] lengthBytes = new byte[4];
        buffer.readBytes(lengthBytes);
        Integer commmandLength = Integer.valueOf(MessageByteUtils.getString(lengthBytes));
        byte[] funcNoData = new byte[2];
        buffer.readBytes(funcNoData);
        String funcNo = new String(funcNoData);
        byte[] seqNoBytes = new byte[4];
        buffer.readBytes(seqNoBytes);
        Integer seqNo = Integer.valueOf(MessageByteUtils.getString(seqNoBytes));

        int bodyLength = commmandLength - HEAD_LENGTH;
        // 判断请求数据包数据是否到齐
        if (buffer.readableBytes() < bodyLength) {
            buffer.readerIndex(beginIndex);
            return;
        }

        byte[] data = new byte[bodyLength];
        buffer.readBytes(data);

        AFSTMessageProtocol protocol = new AFSTMessageProtocol();
        protocol.setCommmandLength(commmandLength);
        protocol.setFuncNo(funcNo);
        protocol.setSeqNo(seqNo);
        protocol.setContent(data);

        buffer.markReaderIndex();
        out.add(protocol);
    }
}
